<template>
  <div class="app-container" :class="{ disabled: disableAction }">
    <div class="top-box-mobile hidden-sm-and-up" :class="{ disabled: deptLoading }">
      <TopSelectMobile v-model="queryParams" :dept-tree="deptTree" :dept-map="deptMap" @change="changeTopSelect" />
      <div class="stats-time" v-if="statsTime"><i class="el-icon-time" />当前数据截止时间：{{ statsTime }}</div>
    </div>
    <el-scrollbar class="scrollbar">
      <div class="top-box-pc hidden-xs-only">
        <TopSelectPc v-model="queryParams" :dept-tree="deptTree" :dept-map="deptMap" @change="changeTopSelect" />
        <div class="stats-time" v-if="statsTime">
          <i class="el-icon-time" />
          <span class="hidden-sm-and-down">当前数据截止时间：</span>
          {{ statsTime }}
        </div>
      </div>

      <section class="section-box">
        <div class="subtitle">
          {{ showDeptTitle }}
          <span class="text-unit">（单位：%）</span>
          <i class="el-icon-loading" v-show="deptLoading" />
        </div>
        <div class="chart-box" :class="{ disabled: deptLoading }">
          <div class="text-center" style="margin-bottom: 15px" v-if="isPrjDim">
            <el-radio-group class="tab-box" size="mini" v-model="prjDataType" @input="getDeptStats()">
              <el-radio-button label="MONTH">月份</el-radio-button>
              <el-radio-button label="CHECKITEM" v-if="queryParams.processType">检查项</el-radio-button>
            </el-radio-group>
          </div>
          <DeptChart ref="deptChart" :data="deptStats" :is-prj-dim="isPrjDim" @barClick="deptBarClick" />
        </div>
      </section>

      <section class="section-box">
        <div class="subtitle">
          {{ showIssueTitle }}
          <span class="text-unit">（单位：个）</span>
          <i class="el-icon-loading" v-show="deptLoading" />
        </div>
        <div class="chart-box" :class="{ disabled: deptLoading }">
          <IssueChart ref="issueChart" :data="issueStats" />
        </div>
      </section>
    </el-scrollbar>
  </div>
</template>
<script>
import moment from 'moment'
import { debounce } from '@/utils'
import { PROCESS_TYPE, handleToken, scoreType2label } from './utils/common'
import { projectTree, deptStats } from './utils/api'
import TopSelectPc from './components/TopSelectPc.vue'
import TopSelectMobile from './components/TopSelectMobile.vue'
import DeptChart from './components/DeptChart.vue'
import IssueChart from './components/IssueChart.vue'
export default {
  name: 'ProjectDashboard',
  components: { TopSelectPc, TopSelectMobile, DeptChart, IssueChart },
  data() {
    return {
      isReady: false,
      deptLoading: false,
      queryParams: {
        deptId: '',
        dataType: '',
        processType: '',
        rdcType: '',
        monthFrom: '',
        monthTo: ''
      },
      treeLoading: false,
      deptTree: [],
      deptMap: {},
      statsTime: '',
      deptStats: [],
      prjDataType: 'MONTH', // CHECKITEM
      issueStats: []
    }
  },
  computed: {
    disableAction() {
      return !this.isReady || this.treeLoading
    },
    currDept() {
      const { deptId } = this.queryParams
      if (!deptId) return {}
      return this.deptMap[deptId] || {}
    },
    isPrjDim() {
      // is project dimension
      return ['MONTH', 'CHECKITEM'].includes(this.queryParams.dataType)
    },
    showDeptTitle() {
      const { deptId } = this.queryParams
      return !deptId ? '各集群检查合格率' : `${this.currDept.label} - 检查合格率`
    },
    showIssueTitle() {
      const { deptId } = this.queryParams
      return !deptId ? '全集团检查项问题占比' : `${this.currDept.label} - 检查项问题占比`
    }
  },
  beforeRouteUpdate(to, from, next) {
    this.initData(to)
    next()
  },
  mounted() {
    this.initData(this.$route)
  },
  methods: {
    async initData(route) {
      this.isReady = false
      const { token, deptId, processType, rdcType, monthFrom, monthTo } = route.query || {}

      this.queryParams.deptId = deptId || ''
      this.queryParams.dataType = ''
      this.queryParams.processType = processType || ''
      this.queryParams.rdcType = rdcType || ''

      if (monthFrom && monthTo) {
        this.queryParams.monthFrom = monthFrom
        this.queryParams.monthTo = monthTo
      } else {
        // 近三个月
        this.queryParams.monthFrom = moment().subtract(3, 'months').startOf('month').format('YYYY-MM')
        this.queryParams.monthTo = moment().startOf('month').format('YYYY-MM')
      }

      this.prjDataType = 'MONTH'
      if (!(await handleToken(token))) return

      await this.getDeptTree()

      if (!deptId) this.queryParams.deptId = this.deptTree[0]?.id || ''
      this.getDeptStats()

      const resizeChart = () => {
        this.$refs.deptChart?.resize()
        this.$refs.issueChart?.resize()
      }
      window.onresize = debounce(resizeChart)

      this.isReady = true
    },
    async getDeptTree() {
      this.treeLoading = true
      const res = await projectTree().catch(() => false)
      this.treeLoading = false
      if (res === false) return (this.deptTree = [])

      const data = res.data || []
      const deptMap = {}
      // 递归加字段
      const recursion = list =>
        list.map(i => {
          i.label = i.name
          i.value = i.id + ''
          i.id = i.id + ''
          deptMap[i.value] = i
          // 直管建管移除下级
          if (i.id === '245') return delete i.children

          if (i.children?.length) recursion(i.children)
        })
      recursion(data)

      let data2 = JSON.parse(JSON.stringify(data))
      const recursion2 = list =>
        list.filter(i => {
          // 过滤掉下级为项目的（dataType 默认 MONTH）
          if (i.dataType === 'MONTH') return false
          if (i.children?.length) i.children = recursion2(i.children)
          if (!i.children?.length) i.children = null
          return true
        })
      data2 = recursion2(data2)

      this.deptTree = data2
      this.deptMap = deptMap
    },
    async getDeptStats() {
      const param = { ...this.queryParams }
      const opt = {
        id: param.deptId,
        processType: param.processType,
        rdcType: param.rdcType,
        startTime: `${param.monthFrom}-01`,
        endTime: moment(`${param.monthTo}-01`).endOf('month').format('YYYY-MM-DD'),
        dataType: this.queryParams.dataType || 'DEPT'
      }
      // 过程分类为总体时，只有月份 tab
      if (!param.processType) this.prjDataType = 'MONTH'
      // dataType: DEPT, PRO, MONTH, CHECKITEM
      if (this.isPrjDim) opt.dataType = this.prjDataType
      // 直管建管固定下级指向
      if (opt.id === '245') opt.dataType = 'PRO'

      this.deptLoading = true
      const res = await deptStats(opt, { 401: '登录状态已过期' }).catch(() => false)
      this.deptLoading = false
      if (res === false) return

      const data = res.data || {}
      const depts = data.deptDataVOS || []
      depts.map(i => {
        i.deptId = i.id + ''
      })

      if (opt.dataType === 'MONTH') {
        depts.map(i => {
          // 将 23-10 改为 23年10月
          const [year, month] = (i.name || '').split('-')
          i.name = `${year}年${+month}月`
        })
      }

      this.statsTime = data.statsTime
      this.deptStats = depts
      this.rawDeptData = data
      this.handleIssueStats()
    },
    handleIssueStats() {
      const { processType } = this.queryParams
      // 重构数据
      let rawData = this.rawDeptData?.progressCount
      if (!rawData) return (this.issueStats = [])

      // 过程分类为土建和精装时，问题占比不展示管理动作；为管理动作时，问题占比只展示管理动作
      if ([PROCESS_TYPE.civil, PROCESS_TYPE.handcover].includes(processType)) delete rawData.gldz
      else if (processType === PROCESS_TYPE.gldz) rawData = { gldz: rawData.gldz }

      const data = []
      Object.keys(rawData).map((scoreType, index) => {
        const obj1 = rawData[scoreType] || {}
        const item = { id: scoreType, label: scoreType2label[scoreType] || '', value: scoreType }
        const list = []
        Object.keys(obj1).map((label2, index2) => {
          const obj2 = obj1[label2] || {}
          const item2 = { id: `${index}_${index2}`, label: label2, num: obj2.num }
          const topList = []
          const childrenItems = obj2.childrenItems || {}
          Object.keys(childrenItems).map((label3, index3) => {
            const obj3 = childrenItems[label3] || {}
            const item3 = { id: `${index}_${index2}_${index3}`, label: label3, num: obj3.num }
            topList.push(item3)
          })
          // 排序
          topList.sort((a, b) => b.num - a.num)
          // 取前五项
          item2.list = topList.slice(0, 5)
          list.push(item2)
        })
        // 排序，取前五项
        list.sort((a, b) => b.num - a.num)
        item.list = list.slice(0, 5)
        data.push(item)
      })
      this.issueStats = data
    },
    changeTopSelect(val) {
      // 更改部门时，清除 dataType
      if (val.key === 'deptId') {
        this.queryParams.dataType = ''
        this.prjDataType = 'MONTH'
      }
      this.getDeptStats()
    },
    deptBarClick(item) {
      // 到项目维度为止
      if (this.isPrjDim) return
      this.queryParams.deptId = item.deptId
      this.queryParams.dataType = item.dataType
      // 用于展示项目名称，组织树不含项目
      if (!this.deptMap[item.deptId]) this.deptMap[item.deptId] = { ...item, label: item.name }
      this.getDeptStats()
    }
  }
}
</script>
<style lang="scss" scoped>
$red: #c9151e;

.disabled {
  pointer-events: none;
}
.app-container {
  background-color: #f2f2f2;
  min-width: 320px;
  height: 100%;
  padding: 0;
  color: #333;
  // 隐藏水平滚动条
  /deep/ {
    .el-scrollbar__wrap {
      overflow-x: hidden;
    }
    .el-scrollbar__bar.is-horizontal {
      display: none;
    }
  }
}
.scrollbar {
  height: 100%;
}
.top-box-mobile {
  &.disabled /deep/ .van-nav-bar__content {
    filter: grayscale(1);
    opacity: 0.9;
  }
  .stats-time {
    font-size: 12px;
    background-color: white;
    padding: 0 0 10px 12px;
  }
}
.top-box-pc {
  padding-top: 10px;
  position: relative;
  .stats-time {
    position: absolute;
    top: 24px;
    right: 12px;
    font-size: 12px;
    color: #606266;
  }
}
.section-box {
  background-color: white;
}
.subtitle {
  font-size: 16px;
  font-weight: bold;
  padding: 12px;
  .text-unit {
    color: #606266;
    font-size: 12px;
    font-weight: normal;
  }
}
.chart-box {
  padding: 20px 12px 30px;
}
// 更改 tab 样式
.tab-box /deep/ {
  .el-radio-button__inner {
    color: $red;
    border-color: $red;
    padding: 6px 10px;
  }
  .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    color: white;
    background-color: $red;
    border-color: $red;
    box-shadow: -1px 0 0 0 $red;
  }
}
@media (max-width: 767.98px) {
  .scrollbar {
    height: calc(100% - 136px);
  }
  .subtitle {
    position: relative;
    color: black;
    background-color: #f2f2f2;
    padding-right: 80px;
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 3px;
      height: 100%;
      background-color: $red;
    }
    .text-unit {
      position: absolute;
      top: 15px;
      right: 0;
      color: #909399;
    }
  }
}
@media (min-width: 768px) {
  .section-box {
    border-radius: 8px;
    margin: 12px;
  }
  .subtitle {
    padding-top: 20px;
  }
}
</style>
